import 'dart:async';

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';

class AnimatedListPage extends StatefulWidget {
  const AnimatedListPage({super.key});

  @override
  State<AnimatedListPage> createState() => _AnimatedListPageState();
}

class _AnimatedListPageState extends State<AnimatedListPage> {
  final _globalKey = GlobalKey<AnimatedListState>();
  bool flag = true;
  List<String> list = [
    "第1条",
    "第2条",
  ];

  Widget _buildItem(index) {
    return ListTile(
      title: Text(
        list[index],
      ),
      trailing: IconButton(
        icon: const Icon(Icons.delete),
        onPressed: () {
          //执行删除
          _deleteItem(index);
        },
      ),
    );
  }

  void _deleteItem(index) {
    if (kDebugMode) {
      print("删除的索引$index");
    }
    if (flag) {
      flag = false;
      _globalKey.currentState!.removeItem(
        index,
        (context, animation) {
          var removeItem = _buildItem(index);
          list.removeAt(index);
          return ScaleTransition(
            // opacity: animation,
            scale: animation,
            child: removeItem,
          );
        },
      );
      Timer.periodic(
        const Duration(milliseconds: 600),
        (timer) {
          flag = true;
          timer.cancel();
        },
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("AnimatedListPage"),
      ),
      body: AnimatedList(
        key: _globalKey,
        initialItemCount: list.length,
        itemBuilder: (context, index, animation) {
          return FadeTransition(
            opacity: animation,
            child: _buildItem(index),
          );
        },
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          list.add("我是新增的呢");
          _globalKey.currentState!.insertItem(list.length - 1);
          // setState(() {
          //   list.add("value");
          // });
        },
        child: const Icon(Icons.add),
      ),
    );
  }
}
